package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	"github.com/Unknwon/goconfig"
	"github.com/gin-gonic/gin"
)

var (
	StartupLogPath     = "/var/log/hello-world/"
	StartupLogFileName = "go-gin-startup.log"
	GlobalConfPath     = "/etc/hello-world/"
	GlobalConfFileName = "global.conf"
	Port               = "80"
	Version            = ""
)

func main() {
	fmt.Printf("App Version:%s\n", Version)

	//1.控制台及启动日志配置
	if yes := IsPathExist(StartupLogPath); !yes {
		os.MkdirAll(StartupLogPath, os.ModePerm)
	}
	logFile, err := os.OpenFile(StartupLogPath+StartupLogFileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, os.ModePerm)
	if err != nil {
		log.Fatal("OpenFile[err]: ", err.Error())
	}
	gin.DefaultWriter = io.MultiWriter(logFile, os.Stdout)

	// 2.创建路由
	Router := gin.Default()

	// 3.绑定路由规则，执行的函数
	Router.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "hello Go-Gin!")
	})
	Router.GET("/favicon.ico", func(c *gin.Context) {
		c.String(http.StatusNoContent, "")
	})

	// 4.从配置获取端口号
	port, _ := GetConfPort(GlobalConfPath, GlobalConfFileName)
	if port != "" {
		Port = port
	}

	// 5.监听端口
	err = Router.Run(":" + Port)
	if err != nil {
		log.Fatal("ListenAndServe[err]: ", err.Error())
	}
}

// GetConfPort 获取配置文件中端口号
func GetConfPort(confPath string, confFileName string) (string, error) {
	if yes := IsPathExist(confPath); !yes {
		os.MkdirAll(confPath, os.ModePerm)
	}

	confFile := confPath + confFileName

	cfg, err := goconfig.LoadConfigFile(confFile)
	if err != nil {
		return "", err
	}

	val, err := cfg.GetValue("global", "port")
	if err != nil {
		return "", err
	}

	return val, nil
}

// IsPathExist 判断path是否存在
func IsPathExist(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}
